package jsudoku;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import jsudoku.exception.InvalidSudokuException;

public class SudokuFileManager {
    private File sudokuFile;

    public SudokuFileManager(File pSudokuFile) {
        if(!pSudokuFile.getName().endsWith(".sdk")){
            this.sudokuFile= new File(pSudokuFile.getAbsolutePath()+".sdk");
        }else{
            this.sudokuFile = pSudokuFile;
        }
    }

    public Sudoku openSudoku() throws FileNotFoundException, IOException, InvalidSudokuException{
        BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(this.sudokuFile)));
        String number=br.readLine();
        char[] numbers=number.toCharArray();
        int[][] sudoku=new int[9][9];
        int cont=0;
        for(int i=0; i<9; i++){ 
            for(int j=0; j<9; j++){
            	/*BUG 5 START*/
            	//BUG 5 RESOLUTION IF - ELSE
            	if(numbers[cont]=='1'||numbers[cont]=='2'||numbers[cont]=='3'||numbers[cont]=='4'
            	   ||numbers[cont]=='5'||numbers[cont]=='6'||numbers[cont]=='7'
            	   ||numbers[cont]=='8'||numbers[cont]=='9'||numbers[cont]=='0'){
            	/*BUG 5 END*/
                sudoku[i][j]=Integer.parseInt(numbers[cont]+"");
                cont++;}
            	/*BUG 5 START*/ 
            	else 
            	throw new InvalidSudokuException();
            	/*BUG 5 END*/
            	
            }
        }
        return new Sudoku(sudoku);
    }

    public void saveSudoku(Sudoku pSudoku) throws IOException{
        if(!this.sudokuFile.exists()){
            this.sudokuFile.createNewFile();
        }
        DataOutputStream dos=new DataOutputStream(new FileOutputStream(this.sudokuFile));
        int[][] sudoku=pSudoku.getSudoku();
        String saveString="";
        for(int i=0; i<9; i++){
            for(int j=0; j<9; j++){
                saveString+=sudoku[i][j];
            }
        }
        dos.writeBytes(saveString);;
    }

}
